package org.diffgenova;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

public class AggiornaTipiRifiuti {
    Map<String, String> rifiutiList = new TreeMap<String, String>();
    Resources resources;
    
    public AggiornaTipiRifiuti(Resources resources) {
        this.resources = resources;
    }
    
    public Map<String, String> aggiorna() throws Exception {
//        getRifiutiFromHtml();
        getRifiutiFromResources();
        
        if(rifiutiList.size() == 0){
        	throw new Exception("Nessuna informazione!");
        }
        return rifiutiList;
    }

	private void getRifiutiFromHtml() throws Exception {
		// String letters = "ABCDEGHILMNOPQRSTUVZ";
        String letters;
        letters = "abc";
        letters = "abcdefghijklmnopqrstuvwxyz";
        for (int i = 0; i < letters.length(); i++) {
        	try {
        		getRifiuti(letters.charAt(i));
			} catch (IOException e) {
	            e.printStackTrace();
	            throw new Exception("Nessuna informazione!");
			}
        }
        
        Log.e("list","<string-array name=\"rifiuti\">");
        for (String rifiuto : rifiutiList.keySet()) {
        	Log.w("list","<item>" + rifiuto + "</item>");
		}
        Log.w("list","</string-array>");
        Log.w("list","<string-array name=\"contenitori\">");
        for (String rifiuto : rifiutiList.keySet()) {
        	Log.w("list","<item>" + rifiutiList.get(rifiuto) + "</item>");
		}
        Log.w("list","</string-array>");
	}
    
    private void getRifiutiFromResources() throws IOException {
    	String[] materiali = resources.getStringArray(R.array.rifiuti);
    	String[] contenitori = resources.getStringArray(R.array.contenitori);
//    	setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, materiali));
        for (int n=0; n < materiali.length; n++) {
        	rifiutiList.put(materiali[n], contenitori[n]);
		}


    }
    
    public void getRifiuti(char letter) throws Exception {
//        Document doc = getLocalPage(letter);
    	Document doc = getNetPage(letter);
    	Elements select = doc.select("div[id~=txt_\\d]");
    	// System.err.println(">>" + select);
    	for (Element contenitore : select) {
    		Element rifiuto = contenitore.previousElementSibling();
    		rifiutiList.put(rifiuto.text().trim(), contenitore.text().trim());
    	}
    }
    
	private Document getLocalPage(char letter) throws IOException {
        AssetManager assetManager = resources.getAssets();
        InputStream is = assetManager.open(letter + ".htm");
        // InputStream is = resources.openRawResource(R.raw.a);
        Document doc = Jsoup.parse(is, "UTF-8",
                                   "http://example.com/");
        return doc;
        
    }
    
    private Document getNetPage(char letter) throws Exception{
    	String html = getHTMLViaHttp("http://www.amiu.genova.it/glossary2.php?content_id=134&letter="
                                             + letter
                );
    	Document doc = Jsoup.parse(html);
        return doc;
    }
    
    private String getHTMLViaHttp(String string) throws Exception {
    	HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(string);
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        in.close();
		return sb.toString();
	}

	private Document getNetOrigPage(char letter) throws IOException {
    	Document doc = Jsoup.connect(
    			"http://www.amiu.genova.it/glossary2.php?content_id=134&letter="
    					+ letter
    			)
    			.userAgent("Mozilla")
    			.timeout(10000)
    			.get();
    	return doc;
    }
    
}
